
package com.eshore.ezone.downloads;

import com.eshore.ezone.utils.HttpManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Map;
import java.util.WeakHashMap;

public class ImageDownloader {
    /**
     * The default maximum number of active tasks.
     */
    public static final int DEFAULT_TASK_LIMIT = 3;

    /**
     * The maximum number of active tasks.
     */
    private static final int MAX_TASK_COUNT = 3;

    /**
     * The default cache size (in bytes).
     */
    // 25% of available memory, up to a maximum of 16MB
    public static final long DEFAULT_CACHE_SIZE = Math.min(Runtime.getRuntime().maxMemory() / 4,
            16 * 1024 * 1024);

    public interface Callback {
        void onImageLoaded(ImageView view, String url);
        void onImageError(ImageView view, String url, Throwable error);
    }

    public static enum BindResult {
        OK, LOADING, ERROR
    }

    private final LinkedList<ImageRequest> mRequests = new LinkedList<ImageRequest>();

    private final Map<String, Bitmap> mBitmaps = Collections
            .synchronizedMap(new ImageCache<String>(DEFAULT_CACHE_SIZE));

    private final Map<ImageView, String> mImageViewBinding = new WeakHashMap<ImageView, String>();

    private int mActiveTaskCount;

    private static ImageDownloader mInstance = new ImageDownloader();

    public ImageDownloader getInstance() {
        return mInstance;
    }

    void flushRequests() {
        while (mActiveTaskCount < MAX_TASK_COUNT && !mRequests.isEmpty()) {
            new ImageTask().execute(mRequests.poll());
        }
    }

    private void enqueueRequest(ImageRequest request) {
        mRequests.add(request);
        flushRequests();
    }

    private void insertRequestAtFrontOfQueue(ImageRequest request) {
        mRequests.add(0, request);
        flushRequests();
    }

    public BindResult bind(BaseAdapter adapter, ImageView view, String url) {
        if (adapter == null) {
            throw new NullPointerException("Adapter is null");
        }
        if (view == null) {
            throw new NullPointerException("ImageView is null");
        }
        if (url == null) {
            throw new NullPointerException("URL is null");
        }
        Bitmap bitmap = getBitmap(url);
        if (bitmap != null) {
            view.setImageBitmap(bitmap);
            return BindResult.OK;
        } else {
            // Clear the ImageView by default.
            // The caller can set their own placeholder
            // based on the return value.
            view.setImageDrawable(null);

            ImageRequest request = new ImageRequest(adapter, url);

            // For adapters, post the latest requests
            // at the front of the queue in case the user
            // has already scrolled past most of the images
            // that are currently in the queue.
            insertRequestAtFrontOfQueue(request);

            return BindResult.LOADING;
        }
    }

    public BindResult bind(BaseExpandableListAdapter adapter, ImageView view, String url) {
        if (adapter == null) {
            throw new NullPointerException("Adapter is null");
        }
        if (view == null) {
            throw new NullPointerException("ImageView is null");
        }
        if (url == null) {
            throw new NullPointerException("URL is null");
        }
        Bitmap bitmap = getBitmap(url);
        if (bitmap != null) {
            view.setImageBitmap(bitmap);
            return BindResult.OK;
        } else {
            // Clear the ImageView by default.
            // The caller can set their own placeholder
            // based on the return value.
            view.setImageDrawable(null);

            ImageRequest request = new ImageRequest(adapter, url);

            // For adapters, post the latest requests
            // at the front of the queue in case the user
            // has already scrolled past most of the images
            // that are currently in the queue.
            insertRequestAtFrontOfQueue(request);

            return BindResult.LOADING;
        }
    }

    public BindResult bind(ImageView view, String url, Callback callback) {
        if (view == null) {
            throw new NullPointerException("ImageView is null");
        }
        if (url == null) {
            throw new NullPointerException("URL is null");
        }
        mImageViewBinding.put(view, url);
        Bitmap bitmap = getBitmap(url);
        if (bitmap != null) {
            view.setImageBitmap(bitmap);
            return BindResult.OK;
        } else {
            // Clear the ImageView by default.
            // The caller can set their own placeholder
            // based on the return value.
            view.setImageDrawable(null);

            ImageRequest request = new ImageRequest(view, url, callback);
            enqueueRequest(request);
            return BindResult.LOADING;

        }
    }

    public void unbind(ImageView view) {
        mImageViewBinding.remove(view);
        view.setImageDrawable(null);
    }

    public void preload(String url) {
        if (url == null) {
            throw new NullPointerException();
        }
        if (null != getBitmap(url)) {
            // The image is already loaded
            return;
        }

        boolean loadBitmap = true;
        ImageRequest task = new ImageRequest(url, loadBitmap);
        enqueueRequest(task);
    }

    public void preload(Cursor cursor, int columnIndex, int start, int end) {
        for (int position = start; position < end; position++) {
            if (cursor.moveToPosition(position)) {
                String url = cursor.getString(columnIndex);
                if (!TextUtils.isEmpty(url)) {
                    preload(url);
                }
            }
        }
    }

    public void prefetch(String url) {
        if (url == null) {
            throw new NullPointerException();
        }
        if (null != getBitmap(url)) {
            // The image is already loaded, therefore
            // it does not need to be prefetched.
            return;
        }

        boolean loadBitmap = false;
        ImageRequest request = new ImageRequest(url, loadBitmap);
        enqueueRequest(request);
    }

    public void prefetch(Cursor cursor, int columnIndex) {
        for (int position = 0; cursor.moveToPosition(position); position++) {
            String url = cursor.getString(columnIndex);
            if (!TextUtils.isEmpty(url)) {
                prefetch(url);
            }
        }
    }

    private void putBitmap(String url, Bitmap bitmap) {
        mBitmaps.put(url, bitmap);
    }

    private Bitmap getBitmap(String url) {
        return mBitmaps.get(url);
    }

    private class ImageRequest {

        private final ImageCallback mCallback;

        private final String mUrl;

        private final boolean mLoadBitmap;

        private Bitmap mBitmap;

        private ImageRequest(String url, ImageCallback callback, boolean loadBitmap) {
            mUrl = url;
            mCallback = callback;
            mLoadBitmap = loadBitmap;
        }

        public ImageRequest(BaseAdapter adapter, String url) {
            this(url, new BaseAdapterCallback(adapter), true);
        }

        public ImageRequest(BaseExpandableListAdapter adapter, String url) {
            this(url, new BaseExpandableListAdapterCallback(adapter), true);
        }

        public ImageRequest(ImageView view, String url, Callback callback) {
            this(url, new ImageViewCallback(view, callback), true);
        }

        public ImageRequest(String url, boolean loadBitmap) {
            this(url, null, loadBitmap);
        }

        private Bitmap loadImage(String url) throws IOException {
            HttpGet get = new HttpGet(url);
            InputStream inputStream = null;
            HttpEntity entity = null;
            try {
                HttpResponse response = HttpManager.execute(get);
                final int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != HttpStatus.SC_OK) {
                    return null;
                }
                entity = response.getEntity();
                if (entity != null) {
                    inputStream = response.getEntity().getContent();
                    final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    return bitmap;
                }
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (entity != null) {
                    entity.consumeContent();
                }
            }

            return null;
        }

        public boolean execute() {
            try {
                if (mCallback != null) {
                    if (mCallback.unwanted()) {
                        return false;
                    }
                }

                mBitmap = getBitmap(mUrl);
                if (mBitmap != null) {
                    return true;
                }

                if (mLoadBitmap) {
                    try {
                        mBitmap = loadImage(mUrl);
                    } catch (OutOfMemoryError e) {
                        mBitmap = loadImage(mUrl);
                    }
                    if (mBitmap == null) {
                        throw new NullPointerException("ContentHandler returned null");
                    }
                    return true;
                } else {
                    mBitmap = null;
                    return false;
                }
            } catch (IOException e) {
                return true;
            } catch (RuntimeException e) {
                return true;
            } catch (Error e) {
                return true;
            }
        }

        public void publishResult() {
            if (mBitmap != null) {
                putBitmap(mUrl, mBitmap);
            }

            if (mCallback != null) {
                mCallback.send(mUrl, mBitmap);
            }
        }
    }

    private interface ImageCallback {
        boolean unwanted();

        void send(String url, Bitmap bitmap);
    }

    private final class ImageViewCallback implements ImageCallback {

        private final ImageView mImageView;

        private final Callback mCallback;

        public ImageViewCallback(ImageView imageView, Callback callback) {
            mImageView = imageView;
            mCallback = callback;
        }

        /** {@inheritDoc} */
        public boolean unwanted() {
            // Always complete the callback
            return false;
        }

        /** {@inheritDoc} */
        public void send(String url, Bitmap bitmap) {
            String binding = mImageViewBinding.get(mImageView);
            if (!TextUtils.equals(binding, url)) {
                // The ImageView has been unbound or bound to a
                // different URL since the task was started.
                return;
            }
            Context context = mImageView.getContext();
            if (context instanceof Activity) {
                Activity activity = (Activity) context;
                if (activity.isFinishing()) {
                    return;
                }
            }
            if (bitmap != null) {
                mImageView.setImageBitmap(bitmap);
                if (mCallback != null) {
                    mCallback.onImageLoaded(mImageView, url);
                }
            }
        }
    }

    private static final class BaseAdapterCallback implements ImageCallback {
        private final WeakReference<BaseAdapter> mAdapter;

        public BaseAdapterCallback(BaseAdapter adapter) {
            mAdapter = new WeakReference<BaseAdapter>(adapter);
        }

        public boolean unwanted() {
            return mAdapter.get() == null;
        }

        public void send(String url, Bitmap bitmap) {
            BaseAdapter adapter = mAdapter.get();
            if (adapter == null) {
                // The adapter is no longer in use
                return;
            }
            if (!adapter.isEmpty()) {
                adapter.notifyDataSetChanged();
            }
        }
    }

    private static final class BaseExpandableListAdapterCallback implements ImageCallback {

        private final WeakReference<BaseExpandableListAdapter> mAdapter;

        public BaseExpandableListAdapterCallback(BaseExpandableListAdapter adapter) {
            mAdapter = new WeakReference<BaseExpandableListAdapter>(adapter);
        }

        /** {@inheritDoc} */
        public boolean unwanted() {
            return mAdapter.get() == null;
        }

        /** {@inheritDoc} */
        public void send(String url, Bitmap bitmap) {
            BaseExpandableListAdapter adapter = mAdapter.get();
            if (adapter == null) {
                // The adapter is no longer in use
                return;
            }
            if (!adapter.isEmpty()) {
                adapter.notifyDataSetChanged();
            } else {
                // The adapter is empty or no longer in use.
                // It is important that BaseAdapter#notifyDataSetChanged()
                // is not called when the adapter is empty because this
                // may indicate that the data is valid when it is not.
                // For example: when the adapter cursor is deactivated.
            }
        }
    }

    private class ImageTask extends AsyncTask<ImageRequest, ImageRequest, Void> {

        @Override
        protected void onPreExecute() {
            mActiveTaskCount++;
        }

        @Override
        protected Void doInBackground(ImageRequest... requests) {
            for (ImageRequest request : requests) {
                if (request.execute()) {
                    publishProgress(request);
                }
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(ImageRequest... values) {
            for (ImageRequest request : values) {
                request.publishResult();
            }
        }

        @Override
        protected void onPostExecute(Void result) {
            mActiveTaskCount--;
            flushRequests();
        }
    }
}
